// subPages/health/recordSize/recordSize.js
import * as echarts from '../../../ec-canvas/echarts';
var util =  require('../../../utils/util.js');
var navListJson = require('../../../data/navListJson');
let LineChart = null
const app = getApp()
Page({

  /**
   * 页面的初始数据
   */
  data: {
    currentTab: 0,
    ec: {
      // lazyLoad: true // 延迟加载
    },
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setDate()
  },

  //设置日期
  setDate:function(){
    var that = this
    let date = util.setTime10(new Date())
    let Y = date.split('-')
    that.setData({
      date: date,
      dateStart: Y[0]- 3,
      dateEnd: date,
      navList: navListJson.recordSizeNavList,
      thList: navListJson.recordSizeThList
    })
    that.getData(date)
  },

  bindDateChange: function(e) {
    var that = this
    that.setData({
      date: e.detail.value,
    })
    this.getData(that.data.date)
  },

  //获得数据
  getData:function(date){
    var that = this
    wx.request({
        url: app.globalData.apiUrl +'/health/lst.java',
        data: {
          userId: app.globalData.userId,
          type : 1,
          time: date
        },
        method: 'get',
        header: {
          'content-type': 'application/json' //默认值
        },
        success: function (res) {
          // console.log(res)
          if(res.data.code == '200'){
            that.processingData(res.data.data.list);
            var isEchart = that.processingEchartData(res.data.data.arr);
            if(isEchart){
              that.setData({
                isData: true,
                isEchart: isEchart
              })
              that.linechartsComponnet = that.selectComponent('#mychartLine');
              LineChart = null
              that.getLineGraphData(that.data.weightData,that.data.weightTime);  //创建图表
            }else{
              that.setData({
                isData: false,
                tipTxt: {
                  tipTxt: '暂无测量数据',
                  tipImg: '/resources/index/noData.png'
                }
              })
            }
          }else{
            util.showModal('提示','数据异常')
            return;
          }
        },
        fail: function (res) {
          console.log("失败",res);
        }
    })
  },

  //处理数据
  processingData:function(list){
    var that = this
    if(list.length != 0){
      for(var i in list){
        var date = list[i].createtime.substring(8,10)
        list[i].createtime = date + '日'
      }
      that.setData({
        isData2: true,
        historyList: list,
      })
    }else{
      that.setData({
        isData2: false,
        tipTxt2: {
          tipTxt2: '暂无测量数据',
          tipImg2: '/resources/index/noData.png'
        }
      })
    }
  },

  //处理图表数据
  processingEchartData:function(arr){
    var that = this
    if(arr.length != 0){
      //体重
      var weightData = [];
      var weightTime = []
      for(var i=0;i<arr.weight.length;i++)
      {
        weightData.push(arr.weight[i].weight)
        var time = util.setTime(arr.weight[i].createtime.substring(0,10))
        weightTime.push(time)
      }
      that.setData({
        weightData: weightData,
        weightTime: weightTime
      })
      //BMI
      var bmiData = [];
      var bmiTime = []
      for(var i=0;i<arr.bmi.length;i++)
      {
        bmiData.push(arr.bmi[i].bmi)
        var time = util.setTime(arr.bmi[i].createtime.substring(0,10))
        bmiTime.push(time)
      }
      that.setData({
        bmiData: bmiData,
        bmiTime: bmiTime
      })
      //腰臀比
      var coreData = [];
      var coreTime = []
      for(var i=0;i<arr.core.length;i++)
      {
        coreData.push(arr.core[i].core)
        var time = util.setTime(arr.core[i].createtime.substring(0,10))
        coreTime.push(time)
      }
      that.setData({
        coreData: coreData,
        coreTime: coreTime
      })
      return true
    }else{
      return false
    }
  },

  //线图表
  getLineGraphData:function(data,time){
    if(data == null || time == null) return;
    var that = this
    if (!LineChart){
      that.init_LineEcharts(data,time); //初始化图表
    }else{
      that.setLineOption(data,time); //更新数据
    }
  },

  //初始化图表
  init_LineEcharts: function (data,time) {
    var that = this
    that.linechartsComponnet.init((canvas, width, height) => {
      // 初始化图表
      LineChart = echarts.init(canvas, null, {
        width: width,
        height: height
      });
      LineChart.showLoading({
        text : '正在努力的读取数据中...'
      });
      // Chart.setLineOption(this.getLineOption());
      that.setLineOption(data,time);
      // LineChart.dispatchAction({
      //   type: 'highlight',
      //   seriesIndex: 0,
      //   dataIndex: 0
      // });
      // 注意这里一定要返回 chart 实例，否则会影响事件处理等
      return LineChart;
    });
  },

  setLineOption: function (data,time) {
    LineChart.clear();  // 清除
    LineChart.setOption(this.getLineOption(data,time));  //获取新数据
  },

  //设置折线图表
  getLineOption: function (data,time) {
    var end = (8 / data.length) * 100
    // 指定图表的配置项和数据
    var option = {
      title : {
        text: '',
        subtext: ''
      },
      grid:{ 
        borderWidth:0,
        x:0,
        y:10,
        x2:30,
        y2:0,
        containLabel: true
      },
      xAxis: { 
        type: 'category',
        show:true,
        boundaryGap:false,
        data : time,
        axisLine:{
          show:false
        },
        axisTick:{
            show:false
        },
        axisLabel:{
            show:true,
            color: 'white',
            interval: 0,
            formatter: '{value}',
            formatter:function(value){
              return util.setTime6(value)
            }
        },
      },
      yAxis: {
        type: 'value',
        boundaryGap:false,
        show:false,
      },
      dataZoom:[
        {
          show: false,
          type:'slider',
          start: 0,
          end: end,
          left:'3%',
          right:'3%',
          maxValueSpan: 10,
        },
        {
          type: 'inside',
        },
      ],
      series : [{
        name:'',
        type:'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle : {
          normal: {
            color: '#fff',
          },
        },
        emphasis:{
          itemStyle:{
              borderWidth: 8,
              borderType:'solid',
              borderColor: 'rgba(246,246,246,0.5)'
          }
        },
        data:data
      }]
    };
    LineChart.hideLoading()
    return option;
  },

  //选择导航栏
  switchNav(event){
    var that = this
    var cur = event.currentTarget.dataset.current;      
    if (that.data.currentTab == cur) {
      return false;
    } else {
      that.setData({
          currentTab: cur
      })
      if(that.data.isEchart){
        that.setEchartsData(cur)
      }
    }
  },

  //给图表赋值
  setEchartsData:function(cur){
    var that = this
    switch (cur) {
      case 0:
        //体重
        that.getLineGraphData(that.data.weightData,that.data.weightTime)
        break;
      case 1:
        //bmi
        that.getLineGraphData(that.data.bmiData,that.data.bmiTime)
        break;
      case 2:
        //腰臀比
        that.getLineGraphData(that.data.coreData,that.data.coreTime)
        break;
    }
  },

  //记录按钮
  recordBtn:function(){
    //返回
    wx.navigateBack({
      delta:1
    })
  },

  //测量分析
  analysis:function(e){
    wx.navigateTo({
      url: '../analysis/analysis?id=' + e.currentTarget.dataset.id
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    LineChart = null
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {
    LineChart = null
  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})